using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace HelloCube.JobEntity
{
    /*
     * 使用JobSystem在工作线程上进行Rotation，而不是主线程
     */
    public partial struct RotationSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<HelloCube.Execute.IJobEntity>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            RotateAndScaleJob job = new RotateAndScaleJob()
            {
                DeltaTime = SystemAPI.Time.DeltaTime,
                ElapsedTime = (float)SystemAPI.Time.ElapsedTime,
            };
            job.Schedule();
        }
    }

    [BurstCompile]
    public partial struct RotateAndScaleJob : IJobEntity
    {
        public float DeltaTime;
        public float ElapsedTime;

        /*
         * PostTransformMatrix : 如果初始尺寸不为 Vector.One, 则会包含该组件
         */
        public void Execute(ref LocalTransform transform, ref PostTransformMatrix postTransformMatrix,
            in RotateSpeed rotateSpeed)
        {
            transform = transform.RotateY(rotateSpeed.RadiansPerSecond * DeltaTime);
            postTransformMatrix.Value = float4x4.Scale(1, math.sin(ElapsedTime), 1);
        }
    }
}